/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.camera.one.v2.initialization;

import java.util.ArrayList;
import java.util.List;

import com.android.camera.async.ConcurrentState;
import com.android.camera.async.Updatable;
import com.android.camera.debug.Log;
import com.android.camera.one.OneCamera.IMetadataResult;
import com.android.camera.one.OneCamera.MetadataListener;
import com.android.camera.one.v2.camera2proxy.TotalCaptureResultProxy;

import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;

/**
 * Distributes metadata to more-specific callbacks.
 */
public class MetadataCallbackBroadcaster implements Updatable<TotalCaptureResultProxy> {
	private static final Log.Tag TAG = new Log.Tag("MetadataBroadcast");
	private ConcurrentState<Boolean> mBroadcastEnable;
	private List<MetadataListener> mBroadcastList = new ArrayList<>();
	
	private static class MetadataWrap implements IMetadataResult {
		private final TotalCaptureResultProxy wrap;

		public MetadataWrap(TotalCaptureResultProxy t) {
			wrap = t;
		}
		
		@Override
		public <T> T get(CaptureResult.Key<T> key) {
			return wrap.get(key);
		}
		
		@Override
		public <T> T get(CaptureRequest.Key<T> key) {
			return wrap.getRequest().get(key);
		}
	}

	public MetadataCallbackBroadcaster(ConcurrentState<Boolean> broadcastEnable) {
		mBroadcastEnable = broadcastEnable;
	}
	
	@Override
	public void update(TotalCaptureResultProxy t) {
		MetadataListener[] array;
		synchronized (this) {
			if (!mBroadcastEnable.get()) {
				return;
			}
			MetadataWrap wrap = new MetadataWrap(t);
			for (MetadataListener temp : mBroadcastList) {
				temp.onMetadataCallback(wrap);
			}
		}
	}
	
	public void addCallback(MetadataListener member) {
		if (member == null) return;
		synchronized (this) {
			mBroadcastList.add(member);
			mBroadcastEnable.update(true);
		}
	}
	
    public void removeCallback(MetadataListener member) {
    	synchronized (this) {
	    	mBroadcastList.remove(member);
	    	if (mBroadcastList.size() == 0) {
	    		mBroadcastEnable.update(false);
	    	}
    	}
	}
}
